package com.dating.activity;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.dating.entities.Me;
import com.dating.libs.client.parttern.doit.OnAuthListener;
import com.dating.libs.web.services.registration.RegistrationCredential;
import com.dating.libs.web.services.registration.RegistrationService;
import com.dating.pref.Constant;
import com.dating.pref.Function;
import com.dating.pref.Pref;

public class Register extends Activity implements OnClickListener{
	public static final String TAG="class: Register";
	
	static Toast mToast;
	Handler mHandler;
	
	Button btnRegister;
	EditText birthday;
	
	private int mYear;
	private int mMonth;
	private int mDay;
	
	private String mLatitude="";
	private String mLongitude="";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.register);
		
		mToast=Toast.makeText(this, "", Toast.LENGTH_SHORT);
		mHandler=new Handler();
		
		btnRegister=(Button)findViewById(R.id.btnRegist);
		btnRegister.setOnClickListener(this);
		
		EditText address=(EditText)findViewById(R.id.address);
		birthday=(EditText)findViewById(R.id.date);
		birthday.setOnClickListener(this);
		birthday.setInputType(InputType.TYPE_NULL);
		
		Dating.ME=Me.getInstance(Dating.ME);
		
		try{
			Location g=Function.getLastGeopoint(this);
			mLatitude=g.getLatitude()+"";
			mLongitude=g.getLongitude()+"";
			Log.e("geo", g.getLatitude()+"-"+g.getLongitude());
			address.setText(g.getLatitude()+"-"+g.getLongitude());
		}catch (NullPointerException e) {
			showToast("can not detect location");
		}
	}
	protected Dialog onCreateDialog(int id) {
		Dialog d=new Dialog(this);
		d.setCancelable(true);
		d.requestWindowFeature(Window.FEATURE_NO_TITLE);
		switch (id) {
		case Constant.DIALOG_LOADING:
			d.setContentView(R.layout.loading);
			d.show();
			break;
		case Constant.DIALOG_DATE:
			final Calendar c = Calendar.getInstance();
		    mYear = c.get(Calendar.YEAR);
		    mMonth = c.get(Calendar.MONTH);
		    mDay = c.get(Calendar.DAY_OF_MONTH);

			d=new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
			break;
		default:
			break;
		}
		return d;
	}
	
	// SUPER METHOD
	private void showToast(String text){
		if(mToast!=null){
			mToast.cancel();
		}
		mToast.setText(text);
		mToast.show();
	}
	private void showToast(Handler _handler,final String text){
		if(_handler==null){
			_handler=new Handler();
		}
		_handler.post(new Runnable() {
			
			
			public void run() {
				showToast(text);
			}
		});
	}
	public String getValueEditText(int id){
		EditText edt=(EditText)findViewById(id);
		return edt.getText().toString();
	}
	// REGISTER LISTENER
	//Datepicker dialog generation  
	private DatePickerDialog.OnDateSetListener mDateSetListener =
	    new DatePickerDialog.OnDateSetListener() {

	        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
	            mYear = year;
	            mMonth = monthOfYear;
	            mDay = dayOfMonth;
	            birthday.setText(mMonth+"/"+mDay+"/"+mYear);
	        }
	};
	OnAuthListener _listener=new OnAuthListener() {
		Me _meTemp=null;
		String password="";
		String email="";
		
		@Override
		public void onStart(String email, String password/*MD5*/) {
			this.password=password;
			this.email=email;
			
			String name=getValueEditText(R.id.name);
			String birthday=getValueEditText(R.id.date);
			String address=getValueEditText(R.id.address);
			
			boolean gender=((RadioButton)(findViewById(R.id.radio_male))).isSelected();
			String _gender=gender?"male":"female";
			_meTemp=new Me(0, "",name,_gender,birthday,email,"",Constant.TYPE_ACCOUNT_DATING ,address,mLatitude,mLongitude,address,Function.getPhoneNumber(Register.this),name, Constant.CTG_ME);
			
			if(!getCredential()){
				showToast(mHandler,"get credential failed! try again!");
				onError(new Exception("can not get credential"));
				return;
			}
			RegistrationService rs=new RegistrationService();
			try {
				if(rs.registryBasicInformation(name, email, password/*MD5*/, gender, birthday, address) && rs.complete()){
					
					//OnComplete
					onComplete(true);
				}else	//this error maybe exits account on server
					onComplete(false);
			} catch (Exception e) {
				onError(e);
			}finally{
				Register.this.removeDialog(Constant.DIALOG_LOADING);
				/*mHandler.post(new Runnable() {
					
					public void run() {
						Register.this.removeDialog(Constant.DIALOG_LOADING);
					}
				});*/
			}
		}
		
		@Override
		public boolean onRequestLogin(String username, String password) {
			
			return false;
		}
		
		
		@Override
		public void onError(Exception e) {
			Log.e(TAG, e.toString());
			removeDialog(Constant.DIALOG_LOADING);
		}
		
		
		@Override
		public void onComplete(boolean success) {
			removeDialog(Constant.DIALOG_LOADING);
			if(success){
				//update current user
				Dating.ME=_meTemp;
				Dating.ME.saveToDb(Register.this);
				
				//update Pref
				Pref.setAuth(Register.this, Dating.ME.AUTH);
				Pref.setUsid(Register.this, Dating.ME.UID);
				Pref.setEmail(Register.this, email);
				Pref.setPassword(Register.this, password);
				Log.e("email:register", Pref.getEmail(Register.this));
				Log.e("password:register:", Pref.getPassword(Register.this));
				
				showToast(mHandler,"Registry complete!");
				mHandler.post(new Runnable() {
					
					public void run() {
						
						//save to db. not include _id
						
						//close Login Activity
						sendBroadcast(new Intent("close_login_activity"));
						//start intent
						Intent dating=new Intent(Register.this, Dating.class);
						Register.this.startActivity(dating);
						Register.this.finish();
					}
				});
			}else{
				showToast(mHandler,"May be this account is exits! Try again!");
			}
		}
		
		@Override
		public void onCancel() {
			
		}

		@Override
		public boolean getCredential() {
			RegistrationService sv=new RegistrationService();
			RegistrationCredential rc;
			try {
				rc = sv.requestRegistryPermission(Function.getDeviceId(Register.this), Constant.TYPE_ACCOUNT_DATING);	//require READ_PHONE_STATE
				Dating.ME.UID=rc.getRid("");
				Dating.ME.AUTH=rc.getAutheToken("");
				Dating.ME.registCredential=rc;
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
	};


	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnRegist:
			showDialog(Constant.DIALOG_LOADING);
			
			//get value for registration
			String _email=getValueEditText(R.id.email);
			String _pass=getValueEditText(R.id.pass);
			String _passMD5=_pass;
//			_passMD5=Function.toMD5(_pass);
			
			//begin registration
			Dating.ME.setOnRegisterListener(_listener);
			
			showDialog(Constant.DIALOG_LOADING);
			Dating.ME.doSYSRegist(_email, _passMD5);
			break;
		case R.id.date:
			showDialog(Constant.DIALOG_DATE);
			break;
		default:
			break;
		}
	}
}
